package com.humanres.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.ciko.code.base.BaseActicity;
import com.ciko.code.bean.User;
import com.ciko.code.constant.Constants;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.AddLeaveFlowReq;
import com.ciko.code.http.Req.GetAllLeaveTypesReq;
import com.ciko.code.http.Req.GetNextPersonReq;
import com.ciko.code.type.EmployeeEnum;
import com.ciko.code.utils.MultiCard;
import com.ciko.code.utils.Util;
import com.mywork.R;
import com.squareup.picasso.Picasso;
import com.ui.dialog.DataTimePicker;
import com.ui.dialog.HeaderImageDialog;

import java.io.File;
import java.util.UUID;


/**
 * Created by 12154 on 2015/11/1.
 */
public class ResLeaveActivity
        extends
        BaseActicity
        implements
        HeaderImageDialog.OnUserinfoMenuClickListener
{
	
	private RelativeLayout	  rectchooseType;
	private RelativeLayout	  rectchooseTimeStart;
	private RelativeLayout	  rectchooseTimeEnd;
							  
	private TextView		  tv_Retroactive;
	private TextView		  tv_endTimeLeave;
	private TextView		  tv_dayCountLeave;
	private TextView		  tv_Job;
	private TextView		  tv_Name;
	private TextView		  tv_startTimeLeave;
	private ImageView		  ivHanderIcon;
							  
	private EditText		  etresonLeave;
							  
	private Button			  btnsubmitLeave;
							  
	private DataTimePicker	  startTimeDialog;
							  
	private long			  startTime	= 0;
	private long			  endTime	= 0;
										
	private DataTimePicker	  endTimeDialog;
							  
	private Spinner			  actv_type;
	private int				  dayCount	= 0;
	private String			  type;
	private String			  reson		= "";
	private HeaderImageDialog imgSetDialog;
	public static File		  mImageFile;		  //图片文件
							  
	User					  nextUser	= null;
										
	@Override
	protected void initTopBar() {
		setTitle("请假申请");
		enableNavLeftImg();
	}
	
	@Override
	protected void initLayout() {
		setContentView(R.layout.activity_res_leave);
	}
	
	@Override
	protected void initView() {
		actv_type = (Spinner) findViewById(R.id.actv_type);
		
		btnsubmitLeave = (Button) findViewById(R.id.btn_submitLeave);
		tv_startTimeLeave = (TextView) findViewById(R.id.tv_startTimeLeave);
		tv_endTimeLeave = (TextView) findViewById(R.id.tv_endTimeLeave);
		tv_dayCountLeave = (TextView) findViewById(R.id.tv_dayCountLeave);
		etresonLeave = (EditText) findViewById(R.id.et_resonLeave);
		rectchooseTimeEnd = (RelativeLayout) findViewById(R.id.rect_chooseTimeEnd);
		rectchooseTimeStart = (RelativeLayout) findViewById(R.id.rect_chooseTimeStart);
		rectchooseType = (RelativeLayout) findViewById(R.id.rect_chooseType);
		//        tv_Retroactive = (TextView) findViewById(R.id.tv_Retroactive);
		ivHanderIcon = (ImageView) findViewById(R.id.ivHanderIcon);
		tv_Job = (TextView) findViewById(R.id.tvJob);
		tv_Name = (TextView) findViewById(R.id.tvName);
		
		imgSetDialog = new HeaderImageDialog(ResLeaveActivity.this, this);
		findViewById(R.id.rlyt_update_img).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				imgSetDialog.show();
			}
		});
		
	}
	
	@Override
	protected void initAdapter() {
	
	}
	
	@Override
	protected void initDates() {
		
		doRequestHttp(new GetAllLeaveTypesReq());
		
		startTimeDialog = new DataTimePicker(ResLeaveActivity.this, listener);
		endTimeDialog = new DataTimePicker(ResLeaveActivity.this, endlistener);
		
		doRequestHttp(new GetNextPersonReq());
	}
	
	@Override
	protected void initListener() {
		rectchooseType.setOnClickListener(this);
		rectchooseTimeStart.setOnClickListener(this);
		rectchooseTimeEnd.setOnClickListener(this);
		
		btnsubmitLeave.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		
		if (v == btnsubmitLeave)
		{
			if (check())
			{
				progressDialog.show();
				doRequestHttp(new AddLeaveFlowReq(type, 0, startTime, endTime, dayCount, reson, "", nextUser.getId(), nextUser.getStaffName()));
			}
		}
		else if (v == rectchooseTimeEnd)
		{
			endTimeDialog.show();
		}
		else if (v == rectchooseTimeStart)
		{
			startTimeDialog.show();
		}
		else if (v == rectchooseType)
		{
		
		}
	}
	
	private boolean check() {
		
		type = actv_type.getSelectedItem().toString();
		
		reson = etresonLeave.getText().toString().trim();
		
		if (type.contains("请选择"))
		{
			showToast("请选择请假类型");
			return false;
		}
		else if (startTime == 0)
		{
			showToast("请选择开始时间");
			return false;
		}
		else if (endTime == 0)
		{
			showToast("请选择结束时间");
			return false;
		}
		else if (dayCount <= 0)
		{
			showToast("结束时间必须大于开始时间");
			return false;
		}
		else if (TextUtils.isEmpty(reson))
		{
			showToast("请填写请假事由");
			return false;
		}
		else if (reson.length() > 50)
		{
			showToast("字数不能超过50字");
			return false;
		}
		else if (null == nextUser)
		{
			showToast("请选择审批人");
			return false;
		}
		
		return true;
	}
	
	@Override
	public void onResponseSuccess(BaseResponse<?> response, String tag) {
		super.onResponseSuccess(response, tag);
		
		switch (tag) {
			case "":
				break;
			case "AddLeaveFlowReq":
				progressDialog.dismiss();
				showToast("提交成功");
				Intent intent = new Intent();
				setResult(1001, intent);
				finish();
				break;
			case "GetNextPersonReq":
				nextUser = (User) response.getReturnObject();
				if (null != nextUser)
				{
					tv_Job.setText(EmployeeEnum.typeOfValue(nextUser.getUserPositionMark()));
					tv_Name.setText(nextUser.getStaffName());
					if (!TextUtils.isEmpty(nextUser.getUserHead()))
					                                                Picasso.with(this).load(nextUser.getUserHead()).into(ivHanderIcon);
					if (nextUser.getUserPositionMark() == 9999) {
						Util.showToast(this, R.string.params_less_tip);
					}
				}
				break;
		}
	}
	
	@Override
	public void openCamera() {
		if (Util.isSDCardSapceForWriteWithTip(ResLeaveActivity.this, MultiCard.TYPE_IMAGE, 0, true)) { return; }
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String fileName = UUID.randomUUID().toString() + ".jpg";
		mImageFile = new File(Util.getWritePathIgnoreError(fileName));
		Uri capturedImgUri = Uri.fromFile(mImageFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImgUri);
		try
		{
			Intent wrapperIntent = Intent.createChooser(intent, null);
			startActivityForResult(wrapperIntent, Constants.CAPTURE_IMAGE);
		}
		catch (ActivityNotFoundException e)
		{
			Util.showToast(ResLeaveActivity.this, "您的手机没有摄像头");
		}
		
	}
	
	@Override
	public void openLocal() {
		if (Util.isSDCardSapceForWriteWithTip(ResLeaveActivity.this, MultiCard.TYPE_IMAGE, 0, true)) { return; }
		Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
		mIntent.setType("image/*");
		Intent wrapperIntent = Intent.createChooser(mIntent, null);
		startActivityForResult(wrapperIntent, Constants.GET_LOCAL_IMAGE);
		
	}
	
	DataTimePicker.OnDateTimeSetListener listener	 = new DataTimePicker.OnDateTimeSetListener()
	                                                 {
		                                                 @Override
		                                                 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth, int hour, int mintue) {
			                                                 String curDate = "" + year + "-" + getTimeString(monthOfYear + 1) + "-" + getTimeString(dayOfMonth) + " " + getTimeString(hour) + ":" + getTimeString(mintue);
			                                                 tv_startTimeLeave.setText(curDate);
			                                                 tv_startTimeLeave.setTextColor(Color.BLACK);
			                                                 startTime = Util.getStringtoDate(curDate).getTime();
															 
			                                                 dipatchTime(startTime, endTime);
		                                                 }
	                                                 };
													 
	DataTimePicker.OnDateTimeSetListener endlistener = new DataTimePicker.OnDateTimeSetListener()
	                                                 {
		                                                 @Override
		                                                 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth, int hour, int mintue) {
			                                                 String curDate = "" + year + "-" + getTimeString(monthOfYear + 1) + "-" + getTimeString(dayOfMonth) + " " + getTimeString(hour) + ":" + getTimeString(mintue);
			                                                 tv_endTimeLeave.setText(curDate);
			                                                 tv_endTimeLeave.setTextColor(Color.BLACK);
			                                                 endTime = Util.getStringtoDate(curDate).getTime();
			                                                 dipatchTime(startTime, endTime);
		                                                 }
	                                                 };
													 
	private String getTimeString(int time) {
		return (time < 10 ? "0" : "") + time;
	}
	
	private void dipatchTime(long startTime, long endTime) {
		if (endTime != 0 && startTime != 0)
		{
			long mss = endTime - startTime;
			int hour = (int) (mss / (60 * 60 * 1000));
			int minutes = (int) (mss % (60 * 60 * 1000));
			
			dayCount = (hour + (minutes == 0 ? 0 : 1));
			
			System.out.println("hour:" + dayCount);
			tv_dayCountLeave.setText(Util.getDayAndHour(dayCount));
		}
	}
	
	@Override
	public void onResponseFail(String tag, int resultCode) {
		super.onResponseFail(tag, resultCode);
		switch (tag) {
			case "AddLeaveFlowReq":
				progressDialog.dismiss();
				Util.showToast(this, "提交失败，请稍后再试");
				break;
				
		}
	}
	
	/**
	 * @param mss
	 *            要转换的毫秒数
	 * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
	 * @author fy.zhang
	 */
	public static String formatDuring(long mss) {
		long days = mss / (1000 * 60 * 60 * 24);
		long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
		long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
		long seconds = (mss % (1000 * 60)) / 1000;
		return days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds ";
	}
	
}
